package Deom;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2023-11-26
 * Time: 19:46
 */
class Money implements Cloneable{
    public double money = 12.5;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class Person implements Cloneable{
    public String name;
    public Money m;
    public Person(String name) {
        this.name = name;
        m = new Money();
    }
    //因为在Person类中并没有clone方法，clone方法只有在Object类中有，所以我们需要重写一个这个方法。
    //因为这个方法在Object类中是受protected保护的，在不同包的子类使用，所以需要super关键字来调用这个clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person) super.clone();
        tmp.m = (Money) this.m.clone();
        return tmp;
    }

    public static void main(String[] args)throws CloneNotSupportedException{
        /*//实例化一个person1对象
        Person person1 = new Person("zhangsan");
        //通过clone克隆一个person2
        Person person2 = (Person)person1.clone();
        System.out.println(person1.name);
        System.out.println(person2.name);*/

        /*Person person1 = new Person("zhangsan");//1
        Person person2 = (Person)person1.clone();//2
        System.out.println("修改前"+person1.m.money);//3
        System.out.println("修改前"+person2.m.money);//4
        person2.m.money = 87.5;//5
        System.out.println("修改后"+person1.m.money);//6
        System.out.println("修改后"+person2.m.money);//7*/


        Person person1 = new Person("zhangsan");
        Person person2 = (Person)person1.clone();
        System.out.println("修改前"+person1.m.money);
        System.out.println("修改前"+person2.m.money);
        person2.m.money = 87.5;//5
        System.out.println("修改后"+person1.m.money);
        System.out.println("修改后"+person2.m.money);
    }
}
